<template>

  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
            v-model="searchForm.name"
            placeholder="名称"
            clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getRoleList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true" v-if="hasAuth('role:add')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
          <template v-slot:reference>
            <el-button type="danger" :disabled="delBtlStatu" v-if="hasAuth('role:delete')">批量删除
            </el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">

      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="name"
          label="名称"
          width="120">
      </el-table-column>
      <el-table-column
          prop="position_obj.name"
          label="所属部门"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          prop="description"
          label="描述"
          show-overflow-tooltip>
      </el-table-column>

      <el-table-column
          prop="is_show"
          label="状态">
        <template v-slot:default="scope">
          <el-tag size="small" v-if="scope.row.is_show" type="success">正常</el-tag>
          <el-tag size="small" v-else-if="scope.row.is_show" type="danger">禁用</el-tag>
        </template>

      </el-table-column>
      <el-table-column
          prop="icon"
          label="操作">

        <template v-slot:default="scope">
          <el-button type="text" @click="permHandle(scope.row.id)">分配权限</el-button>
          <el-divider direction="vertical"></el-divider>

          <el-button type="text" @click="editHandle(scope.row.id)" v-if="hasAuth('role:update')">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.id)"
                           v-if="hasAuth('role:delete')">
              <template v-slot:reference>
                <el-button type="text">删除</el-button>
              </template>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>

    </el-table>


    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="page"
        :page-size="size"
        :total="total">
    </el-pagination>


    <!--新增对话框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-editForm"
               size="small">

        <el-form-item label="角色名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="description" label-width="100px">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门:" prop="position">
          <treeselect
              style="width: 170px"
              placeholder="选择部门"
              v-model="editForm.position"
              :options="deptData"
              :normalizer="normalizer"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="editForm.is_show">
            <el-radio :label='false'>禁用</el-radio>
            <el-radio :label='true'>正常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editForm')">立即创建</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog
        title="分配权限"
        :visible.sync="permDialogVisible"
        width="600px">

      <el-form :model="permForm">
        <el-tree
            :data="permTreeData"
            show-checkbox
            ref="permTree"
            :default-expand-all=true
            node-key="id"
            :check-strictly=true
            :props="defaultProps">
        </el-tree>

      </el-form>

      <span slot="footer" class="dialog-footer">
			    <el-button @click="permDialogVisible = false">取 消</el-button>
			    <el-button type="primary" @click="submitPermFormHandle('permForm')">确 定</el-button>
			</span>

    </el-dialog>

  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {api} from "@/assets/static/js/settings";

export default {
  name: "Role",
  data() {
    return {
      searchForm: {},
      delBtlStatu: true,

      total: 0,
      size: 10,
      page: 1,

      dialogVisible: false,
      editForm: {},

      tableData: [],

      editFormRules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        position: [
          {required: true, message: '请输入部门', trigger: 'blur'}
        ],
      },

      multipleSelection: [],

      permDialogVisible: false,
      permForm: {},
      defaultProps: {
        children: 'menus',
        label: 'title'
      },
      permTreeData: [],

      data_scope_show: false,
      // 部门数据
      deptData: [],

    }
  },
  created() {
    this.getRoleList()
    this.$axios.get(api.menu_list).then(res => {
      if (res) {
        this.permTreeData = res.results
      }
    })
    // 获取所有部门
    this.$axios.get(api.position_list).then(res => {
      if (res) {
        this.deptData = res.results
      }
    })
  },
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.menus
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.delBtlStatu = val.length === 0
    },
    handleSizeChange(val) {
      this.size = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      } else {
        console.error('Form reference is not defined');
      }
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },

    getRoleList() {
      this.$axios.get(api.role, {
        params: {
          name: this.searchForm.name,
          page: this.page,
          size: this.size
        }
      }).then(res => {
        if (res) {
          this.tableData = res.results
          this.total = res.count
        }
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          delete this.editForm.menus
          let post_type = this.editForm.id ? this.$axios.put : this.$axios.post
          post_type(api.role + (this.editForm.id ? this.editForm.id + '/' : ''), this.editForm)
              .then(res => {
                if (res) {
                  this.$message({
                    showClose: true,
                    message: '恭喜你，操作成功',
                    type: 'success',
                    onClose: () => {
                      this.getRoleList()
                    }
                  });
                  this.dialogVisible = false
                  this.resetForm(formName)
                }
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取单个角色数据
    editHandle(id) {
      this.$axios.get(api.role + id + '/').then(res => {
        if (res) {
          this.editForm = res.results
          this.dialogVisible = true
        }
      })
    },
    // 删除单个
    delHandle(id) {
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      this.$axios.post(api.role_batch_delete, {ids: ids}).then(res => {
        if (res) {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
              this.getRoleList()
            }
          });
        }
      })
    },
    // 权限查询
    permHandle(id) {
      this.permDialogVisible = true
      this.$axios.get(api.role + id + '/').then(res => {
        if (res) {
          this.$refs.permTree.setCheckedKeys(res.results.menu_list)
          this.permForm = res.results
        }
      })
    },
    // 提交分配权限
    submitPermFormHandle(formName) {
      this.editForm.menu_list = this.$refs.permTree.getCheckedKeys()
      this.$axios.put(api.role + this.permForm.id + '/', this.editForm).then(res => {
        if (res) {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose: () => {
              this.getRoleList()
            }
          });
          this.permDialogVisible = false
          this.resetForm(formName)
        }
      })
    },
  },
  components: {
    Treeselect
  }
}
</script>

<style scoped>

</style>